package com.newland.rbac.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newland.rbac.model.User;
import com.newland.rbac.service.MenuService;
import com.newland.rbac.service.UserService;
import com.newland.rbac.utils.MenuUtil;
import com.newland.rbac.vo.MenuVo;
import com.newland.utils.AjaxResponse;
import com.newland.utils.CustomExceptionType;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("common")
@Slf4j
public class CommonController {
    @Autowired
    private MenuService menuService;

    @Autowired
    private UserService userService;

    @PostMapping("getMenus")
    @RequiresAuthentication
    public AjaxResponse getMenu(String principal){
        List<MenuVo> menus = menuService.getMenu(principal);
        List<MenuVo> menuVos = MenuUtil.buildMenuTree(menus);
        return AjaxResponse.success(menuVos);
    }

    @PostMapping("getUserByPrincipal")
    @RequiresAuthentication
    public AjaxResponse getUserByUserName(String principal){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("name",principal);
        User user = userService.getOne(userQueryWrapper);
        if(user!=null){
            return AjaxResponse.success(user);
        }else{
            return AjaxResponse.error(CustomExceptionType.USER_INPUT_ERROR,"未找到该用户");
        }
    }
}
